import { getAllRoleList, isAccountExist } from '@/api/demo/system';
import { BasicColumn, FormSchema } from '@/components/Table';
import { h } from 'vue';
import { Switch } from 'ant-design-vue';
import { setRoleStatus } from '@/api/demo/system';
import { useMessage } from '@/hooks/web/useMessage';
import { Tinymce } from '@/components/Tinymce';
import dayjs from 'dayjs';
import { uploadApi } from '@/api/sys/upload';

type CheckedType = boolean | string | number;

/**
 * transform mock data
 * {
 *  0: '华东分部',
 * '0-0': '华东分部-研发部'
 * '0-1': '华东分部-市场部',
 *  ...
 * }
 */
export const deptMap = (() => {
  const pDept = ['华东分部', '华南分部', '西北分部'];
  const cDept = ['研发部', '市场部', '商务部', '财务部'];

  return pDept.reduce((map, p, pIdx) => {
    map[pIdx] = p;

    cDept.forEach((c, cIndex) => (map[`${pIdx}-${cIndex}`] = `${p}-${c}`));

    return map;
  }, {});
})();

export const columns: BasicColumn[] = [
  {
    title: '商品图片',
    dataIndex: 'imgs',
    width: 140
  },
  {
    title: '商品名称',
    dataIndex: 'account',
    align: 'left'
  },
  {
    title: '所属类目',
    dataIndex: 'dept',
    customRender: ({ value }) => {
      return deptMap[value];
    },
    width: 100,
  },
  {
    title: '浏览',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '收藏',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '评论',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '审核状态',
    dataIndex: 'status',
    width: 120,
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      return h(Switch, {
        checked: record.status === '1',
        checkedChildren: '已审核',
        unCheckedChildren: '待审核',
        loading: record.pendingStatus,
        onChange(checked: CheckedType) {
          record.pendingStatus = true;
          const newStatus = checked ? '1' : '0';
          const { createMessage } = useMessage();
          setRoleStatus(record.id, newStatus)
            .then(() => {
              record.status = newStatus;
              createMessage.success(`已成功修改角色状态`);
            })
            .catch(() => {
              createMessage.error('修改角色状态失败');
            })
            .finally(() => {
              record.pendingStatus = false;
            });
        },
      });
    },
  },
  {
    title: '发布人',
    dataIndex: 'statu1s',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'id',
    width: 180,
    sorter: true,
    customRender: ({record})=>{
      return record.createTime;
    }
  },
];

export const searchFormSchema: FormSchema[] = [
  {
    field: '[startDate, endDate]',
    label: '日期范围',
    labelWidth: 80,
    component: 'RangePicker',
    colProps: { xs: 24, xl: 12, lg: 8, xxl: 6 },
    componentProps: {
      format: 'YYYY-MM-DD HH:mm:ss',
      placeholder: ['开始时间', '结束时间'],
      showTime: { format: 'HH:mm:ss' },
    },
    defaultValue:[dayjs(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - 7)).format('YYYY-MM-DD'),dayjs(new Date()).format('YYYY-MM-DD')]
  },
  {
    field: 'name',
    label: '商品名称',
    labelWidth: 80,
    component: 'Input',
    colProps: { xs: 24, xl: 12, lg: 8, xxl: 6 },
  },
];


export const goodsFormSchema: FormSchema[] = [
  {
    field: 'dept',
    label: '所属类目',
    component: 'TreeSelect',
    componentProps: {
      fieldNames: {
        label: 'deptName',
        value: 'id',
      },
      getPopupContainer: () => document.body,
    },
    required: false,
  },
  {
    field: 'account',
    label: '商品名称',
    component: 'Input',
    helpMessage: ['本字段演示异步验证', '不能输入带有admin的用户名'],
    rules: [
      {
        required: true,
        message: '请输入用户名',
      },
      {
        trigger: 'blur',
        validator(_, value) {
          return new Promise((resolve, reject) => {
            if (!value) return resolve();
            isAccountExist(value)
              .then(resolve)
              .catch((err) => {
                reject(err.message || '验证失败');
              });
          });
        },
      },
    ],
  },
  // {
  //   label: '角色',
  //   field: 'role',
  //   component: 'ApiSelect',
  //   componentProps: {
  //     api: getAllRoleList,
  //     labelField: 'roleName',
  //     valueField: 'roleValue',
  //   },
  //   required: true,
  // },
  {
    field: 'field23',
    component: 'ImageUpload',
    label: '封面图',
    required: true,
    defaultValue: [
      'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    ],
    componentProps: {
      api: uploadApi,
      accept: ['png', 'jpeg', 'jpg'],
      maxSize: 5,
      maxNumber: 3,
    },
    // rules: [
    //   {
    //     required: true,
    //     trigger: 'change',
    //     validator(_, value) {
    //       if (isArray(value) && value.length > 0) {
    //         return Promise.resolve();
    //       } else {
    //         return Promise.reject('请选择上传图片');
    //       }
    //     },
    //   },
    // ],
  },
  {
    field: 'status',
    component: 'RadioGroup',
    label: '上架状态',
    defaultValue: '1',
    componentProps: {
      options: [
        {
          label: '上架',
          value: '1',
        },
        {
          label: '下架',
          value: '0',
        },
      ],
    },
    rules: [{ required: true, message: '覆盖默认生成的校验信息' }],
  },
  
];

export const saleAttrFormSchema: FormSchema[] = [
  {
    field: 'spec',
    label: '',
    component: 'Input',
    required: true,
    defaultValue: [],
    slot: 'spec'
  },
  {
    field: 'skus',
    label: '',
    component: 'Input',
    required: false,
    defaultValue: [],
    slot: 'skus'
    // ifShow: false
  },
];

export const goodsAttrFormSchema: FormSchema[] = [
  {
    field: 'attribute',
    label: '商品属性',
    component: 'Input',
    required: false,
    defaultValue: [],
    slot: 'attribute'
  },
];


export const detailFormSchema: FormSchema[] = [
  {
    field: 'description',
    component: 'Input',
    label: ' ',
    labelWidth:1,
    defaultValue: 'defaultValue',
    rules: [{ required: true }],
    render: ({ model, field }) => {
      return h(Tinymce, {
        value: model[field],
        onChange: (value: string) => {
          model[field] = value;
        },
      });
    },
  },
]
